package cn.harry.cabinet.viewmodel

import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.harry.cabinet.SmartCabinetApplication
import cn.harry.cabinet.model.entity.Configuration
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.server.KtorServer
import cn.harry.cabinet.utils.IpUtil
import cn.harry.cabinet.utils.AppConfigKeys
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 网络配置ViewModel
 * 负责管理Ktor服务器的启动、停止和网络状态检查
 */
class NetworkViewModel(application: Application) : AndroidViewModel(application) {
    
    private val ktorServer = SmartCabinetApplication.ktorServer
    private val configRepository = ConfigurationRepository(application)
    
    // LiveData for UI updates
    private val _serverStatus = MutableLiveData<String>("服务器未运行")
    val serverStatus: LiveData<String> = _serverStatus
    
    private val _isServerRunning = MutableLiveData<Boolean>(false)
    val isServerRunning: LiveData<Boolean> = _isServerRunning
    
    private val _networkStatus = MutableLiveData<String>("点击按钮检查网络状态")
    val networkStatus: LiveData<String> = _networkStatus
    
    private val _currentPort = MutableLiveData<Int>(KtorServer.DEFAULT_PORT)
    val currentPort: LiveData<Int> = _currentPort
    
    private val _currentHost = MutableLiveData<String>(KtorServer.DEFAULT_HOST)
    val currentHost: LiveData<String> = _currentHost
    
    private val _externalApiUrl = MutableLiveData<String>("")
    val externalApiUrl: LiveData<String> = _externalApiUrl
    
    private val _token = MutableLiveData<String>("")
    val token: LiveData<String> = _token
    
    private val _externalApiEnabled = MutableLiveData<Boolean>(false)
    val externalApiEnabled: LiveData<Boolean> = _externalApiEnabled
    
    init {
        // 初始化默认值已在LiveData声明处设置
        updateServerStatus()
        // 延迟检查网络状态，避免在初始化时出现问题
        // 加载外部接口地址和Token
        loadExternalApiUrl()
        loadToken()
        loadExternalApiEnabled()
        // 加载服务器端口与主机配置
        loadServerConfig()
    }
    
    /**
     * 启动服务器
     */
    fun startServer(port: Int = KtorServer.DEFAULT_PORT, host: String = KtorServer.DEFAULT_HOST) {
        // 立即更新UI状态，显示正在启动
        _serverStatus.postValue("正在启动服务器...")
        
        CoroutineScope(Dispatchers.IO).launch {
            try {
                ktorServer.start(port, host)
                _currentPort.postValue(port)
                _currentHost.postValue(host)
                // 持久化保存端口与主机
                saveServerConfig(port, host)
                // 等待一小段时间确保服务器完全启动
                delay(500)
                updateServerStatus()
                // 启动服务器后自动检查网络状态
                checkNetworkStatus()
            } catch (e: Exception) {
                _serverStatus.postValue("启动服务器失败: ${e.message}")
                _isServerRunning.postValue(false)
            }
        }
    }
    
    /**
     * 停止服务器
     */
    fun stopServer() {
        // 立即更新UI状态，显示正在停止
        _serverStatus.postValue("正在停止服务器...")
        _isServerRunning.postValue(false)
        
        CoroutineScope(Dispatchers.IO).launch {
            try {
                ktorServer.stop()
                // 等待服务器完全停止
                delay(1500)
                updateServerStatus()
            } catch (e: Exception) {
                _serverStatus.postValue("停止服务器失败: ${e.message}")
                // 即使出错也要更新状态
                updateServerStatus()
            }
        }
    }
    
    /**
     * 更新服务器状态
     */
    private fun updateServerStatus() {
        val isRunning = ktorServer.isRunning()
        _isServerRunning.postValue(isRunning)
        
        if (isRunning) {
            val host = _currentHost.value ?: KtorServer.DEFAULT_HOST
            val port = _currentPort.value ?: KtorServer.DEFAULT_PORT
            _serverStatus.postValue("服务器运行中 - http://$host:$port")
        } else {
            _serverStatus.postValue("服务器未运行")
        }
    }
    
    /**
     * 检查网络状态
     */
    fun checkNetworkStatus() {
        try {
            val context = getApplication<Application>()
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            
            // 使用兼容性更好的方法检查网络状态
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            val networkStatus = when {
                activeNetworkInfo == null -> "无网络连接"
                !activeNetworkInfo.isConnected -> "网络未连接"
                activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI -> "WiFi连接"
                activeNetworkInfo.type == ConnectivityManager.TYPE_MOBILE -> "移动网络连接"
                activeNetworkInfo.type == ConnectivityManager.TYPE_ETHERNET -> "以太网连接"
                else -> "其他网络连接"
            }
            
            val localIp = IpUtil.getLocalIpAddress()
            val ipInfo = if (localIp != null) "\n本地IP地址: $localIp" else "\n无法获取本地IP地址"
            
            _networkStatus.postValue("$networkStatus$ipInfo")
        } catch (e: Exception) {
            _networkStatus.postValue("网络状态检查失败: ${e.message}")
        }
    }
    
    /**
     * 应用网络配置并自动重启服务器
     */
    fun applyNetworkConfig(port: Int, host: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 如果服务器正在运行，先停止
                if (ktorServer.isRunning()) {
                    ktorServer.stop()
                    // 等待服务器完全停止
                    delay(1000)
                }
                
                // 使用新配置启动服务器
                ktorServer.start(port, host)
                _currentPort.postValue(port)
                _currentHost.postValue(host)
                // 持久化保存端口与主机
                saveServerConfig(port, host)
                // 等待服务器完全启动后再更新状态
                delay(500)
                updateServerStatus()
                // 应用配置后自动检查网络状态
                checkNetworkStatus()
            } catch (e: Exception) {
                _serverStatus.postValue("应用配置失败: ${e.message}")
            }
        }
    }
    
    /**
     * 获取服务器信息
     */
    fun getServerInfo(): String {
        return if (ktorServer.isRunning()) {
            val host = _currentHost.value ?: KtorServer.DEFAULT_HOST
            val port = _currentPort.value ?: KtorServer.DEFAULT_PORT
            """
            服务器信息：
            • 状态：运行中
            • 地址：http://$host:$port
            • 支持CORS
            • JSON格式
            • 用户管理API
            
            API接口：
            • GET /api/users - 获取所有用户
            • GET /api/users/{id} - 获取指定用户
            • GET /api/users/search?query={query} - 搜索用户
            • POST /api/users - 创建用户
            • PUT /api/users/{id} - 更新用户
            • DELETE /api/users/{id} - 删除用户
            """.trimIndent()
        } else {
            """
            服务器信息：
            • 状态：未运行
            • 端口：${_currentPort.value ?: KtorServer.DEFAULT_PORT}
            • 主机：${_currentHost.value ?: KtorServer.DEFAULT_HOST}
            • 支持CORS
            • JSON格式
            • 用户管理API
            """.trimIndent()
        }
    }
    
    private fun loadExternalApiUrl() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                var config = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_EXTERNAL_API_URL
                )
                if (config == null) {
                    // 不存在则创建默认配置
                    config = Configuration(
                        type = AppConfigKeys.TYPE_NETWORK,
                        key = AppConfigKeys.KEY_NETWORK_EXTERNAL_API_URL,
                        value = ""
                    )
                    configRepository.create(config)
                }
                _externalApiUrl.postValue(config.value ?: "")
            } catch (e: Exception) {
                // ignore load error, keep empty
            }
        }
    }
    
    private fun loadToken() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                var config = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_TOKEN
                )
                if (config == null) {
                    // 不存在则创建默认配置
                    config = Configuration(
                        type = AppConfigKeys.TYPE_NETWORK,
                        key = AppConfigKeys.KEY_NETWORK_TOKEN,
                        value = ""
                    )
                    configRepository.create(config)
                }
                _token.postValue(config.value ?: "")
            } catch (e: Exception) {
                // ignore load error, keep empty
            }
        }
    }

    private fun loadServerConfig() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 默认配置
                val defaultPort = KtorServer.DEFAULT_PORT
                val defaultHost = KtorServer.DEFAULT_HOST
                
                // 加载端口配置
                var portConfig = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_SERVER_PORT
                )
                if (portConfig == null) {
                    // 不存在则创建默认配置
                    portConfig = Configuration(
                        type = AppConfigKeys.TYPE_NETWORK,
                        key = AppConfigKeys.KEY_NETWORK_SERVER_PORT,
                        value = defaultPort.toString()
                    )
                    configRepository.create(portConfig)
                }
                val portValue = portConfig.value?.toIntOrNull() ?: defaultPort
                if (portValue in 1..65535) {
                    _currentPort.postValue(portValue)
                }
                
                // 加载主机配置
                var hostConfig = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_SERVER_HOST
                )
                if (hostConfig == null) {
                    // 不存在则创建默认配置
                    hostConfig = Configuration(
                        type = AppConfigKeys.TYPE_NETWORK,
                        key = AppConfigKeys.KEY_NETWORK_SERVER_HOST,
                        value = defaultHost
                    )
                    configRepository.create(hostConfig)
                }
                val hostValue = hostConfig.value
                if (!hostValue.isNullOrBlank()) {
                    _currentHost.postValue(hostValue)
                }
            } catch (_: Exception) {
                // ignore load errors
            }
        }
    }

    private fun saveServerConfig(port: Int, host: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 保存端口
                val existingPort = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_SERVER_PORT
                )
                if (existingPort == null) {
                    configRepository.create(
                        Configuration(
                            type = AppConfigKeys.TYPE_NETWORK,
                            key = AppConfigKeys.KEY_NETWORK_SERVER_PORT,
                            value = port.toString()
                        )
                    )
                } else {
                    configRepository.update(existingPort.copy(value = port.toString(), updateTime = java.util.Date()))
                }
                // 保存主机
                val existingHost = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_SERVER_HOST
                )
                if (existingHost == null) {
                    configRepository.create(
                        Configuration(
                            type = AppConfigKeys.TYPE_NETWORK,
                            key = AppConfigKeys.KEY_NETWORK_SERVER_HOST,
                            value = host
                        )
                    )
                } else {
                    configRepository.update(existingHost.copy(value = host, updateTime = java.util.Date()))
                }
            } catch (_: Exception) {
                // ignore save errors
            }
        }
    }
    
    fun saveExternalApiUrl(url: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val exists = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_EXTERNAL_API_URL
                )
                if (exists == null) {
                    configRepository.create(
                        Configuration(type = AppConfigKeys.TYPE_NETWORK, key = AppConfigKeys.KEY_NETWORK_EXTERNAL_API_URL, value = url)
                    )
                } else {
                    configRepository.update(
                        exists.copy(value = url, updateTime = java.util.Date())
                    )
                }
                _externalApiUrl.postValue(url)
            } catch (e: Exception) {
                // could log error
            }
        }
    }
    
    fun saveToken(token: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val exists = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_TOKEN
                )
                if (exists == null) {
                    configRepository.create(
                        Configuration(type = AppConfigKeys.TYPE_NETWORK, key = AppConfigKeys.KEY_NETWORK_TOKEN, value = token)
                    )
                } else {
                    configRepository.update(
                        exists.copy(value = token, updateTime = java.util.Date())
                    )
                }
                _token.postValue(token)
            } catch (e: Exception) {
                // could log error
            }
        }
    }
    
    private fun loadExternalApiEnabled() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                var config = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_EXTERNAL_API_ENABLED
                )
                if (config == null) {
                    // 不存在则创建默认配置
                    config = Configuration(
                        type = AppConfigKeys.TYPE_NETWORK,
                        key = AppConfigKeys.KEY_NETWORK_EXTERNAL_API_ENABLED,
                        value = "false"
                    )
                    configRepository.create(config)
                }
                _externalApiEnabled.postValue(config.value?.toBoolean() ?: false)
            } catch (e: Exception) {
                // ignore load error, keep false
            }
        }
    }
    
    fun saveExternalApiEnabled(enabled: Boolean) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val exists = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_NETWORK,
                    AppConfigKeys.KEY_NETWORK_EXTERNAL_API_ENABLED
                )
                if (exists == null) {
                    configRepository.create(
                        Configuration(
                            type = AppConfigKeys.TYPE_NETWORK,
                            key = AppConfigKeys.KEY_NETWORK_EXTERNAL_API_ENABLED,
                            value = enabled.toString()
                        )
                    )
                } else {
                    configRepository.update(
                        exists.copy(value = enabled.toString(), updateTime = java.util.Date())
                    )
                }
                _externalApiEnabled.postValue(enabled)
            } catch (e: Exception) {
                // could log error
            }
        }
    }
    
    /**
     * ViewModel销毁时的清理工作
     */
    override fun onCleared() {
        super.onCleared()
        // 服务器由Application管理，不需要在这里停止
    }
} 